//
//  ToutiaoSpeciaTableController.m
//  BobNews
//
//  Created by lanou3g on 16/5/6.
//  Copyright © 2016年 liu. All rights reserved.
//

#import "ToutiaoSpeciaTableController.h"
#import "NetWorkRequestManager.h"
//#import "ToutiaoSpeacialModel.h"
//#import "ToutiaoSpecialModelCell.h"
#import "UIImageView+WebCache.h"
#import "ToutiaoArticleViewController.h"

#import "ToutiaoModel.h"

#import "ToutiaoModelCell.h"
#import "ToutiaoImageModelCell.h"
#import "ToutiaoMulImgModelCell.h"

/// 刷新
#import "LORefresh.h"

@interface ToutiaoSpeciaTableController ()
@property (nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic,strong) NSArray *topicsArray;
@property (nonatomic,strong) NSDictionary *dictionary;

//@property (nonatomic,strong) NSNumber *start;

@end

@implementation ToutiaoSpeciaTableController

- (void)dealloc {
    [self.tableView removeObserver:[self.tableView defaultHeader] forKeyPath:@"contentOffset"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.title = self.navTitle;
    
    self.dataSource = [[NSMutableArray alloc]init];
    self.topicsArray = [NSArray array];
    self.dictionary = [NSDictionary dictionary];
    
    [self analyticalData];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ToutiaoImageModelCell" bundle:nil] forCellReuseIdentifier:@"ToutiaoImageModel"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ToutiaoMulImgModelCell" bundle:nil] forCellReuseIdentifier:@"ToutiaoMulImgModel"];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    [self addRefresh];
}

- (void)addRefresh {
    
    __weak typeof(self)weakSelf = self;
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        [weakSelf.dataSource removeAllObjects];
        
        [weakSelf.tableView reloadData];
        
        [weakSelf analyticalData];
    }];
}

- (void)analyticalData {
    NSString *str = [NSString stringWithFormat:@"http://c.3g.163.com/nc/special/%@.html",self.specialID];
    [NetWorkRequestManager requestUrl:[NSURL URLWithString:str] RequestMethod:GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
            NSMutableDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dataDic = jsonDic[self.specialID];
            self.dictionary = dataDic;
            NSArray *topicsArray = dataDic[@"topics"];
            self.topicsArray = topicsArray;
            for (NSDictionary *dic in topicsArray) {
                NSArray *docsArray = dic[@"docs"];
                for (NSDictionary *itemDic in docsArray) {
                    ToutiaoModel *model = [ToutiaoModel modelWithDictionary:itemDic];
                    [self.dataSource addObject:model];
                    
                }
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                
                [[self.tableView defaultHeader]endRefreshing];
            });
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.dataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [ToutiaoModelCell cellWithTableView:tableView Model:self.dataSource[indexPath.row] IndexPath:indexPath];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 2;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView  = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 100)];
    self.tableView.tableHeaderView = headerView;
    
    UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 100)];
    [imgView sd_setImageWithURL:[NSURL URLWithString:self.dictionary[@"banner"]]];
    [headerView addSubview:imgView];
    return headerView;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ToutiaoArticleViewController *articalVC = [[ToutiaoArticleViewController alloc]init];
    articalVC.docid = [self.dataSource[indexPath.row] docid];
    articalVC.navTitle = [self.dataSource[indexPath.row] title];
    articalVC.model = self.dataSource[indexPath.row];
    [self.navigationController pushViewController:articalVC animated:YES];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
